<?php
/**
 * 实现搜索框功能的控制器 
 */
class SearchController extends AppController{
	
	var $name = "Search";
	var $uses = array('Blog','Userinfo','Tag');
		/** 
		* 处理nickname
		* 
	 */
	 function handle_nickname(&$blogs){
		$n = count($blogs);
		for($i = 0;$i<$n;$i++)
		{
			$uid = $blogs[$i]['Blog']['uid'];
			$nickname = $this->User->query("select nickname from userinfos where id = $uid");
			$blogs[$i]['Blog']['nickname'] = $nickname[0]['userinfos']['nickname'];
		}
	 }
	/**
	 * tag 通过文章标签搜索文章
	 * 传入:标签名从$_GET['get']中传入,
	 * 返回:
	 *     成功:返回一个包含博客json数组
	 *     失败:返回0
	 * @access public
	 * @return void
	 */
	 
	function tag(){
		$this->autoLayout = false;
		$this->autoRender = false;
		if(isset($_GET['sqlName'])){
			$sql = "SELECT * FROM blogs as Blog where keywords LIKE '%{$_GET['sqlName']}%'";
			$result = $this->Blog->query($sql);
			 if(empty($result)){
				 echo '0';
			}else{
				$this->handle_nickname($result);
				echo json_encode($result);
			}
		};
		
	}
	//获取搜索人的标签处理
	function handle_tag(&$results){
		$n = count($results);
		for($i = 0;$i<$n;$i++)
		{
			$user_id = $results[$i]['User']['id'];
			$tag = $this->Tag->query("select tag from tags where user_id = $user_id");
			$num = count($tag);
			for($j = 0;$j<$num;$j++){
				$results[$i]['User']['tag'][$j] =$tag[$j]['tags']['tag'];
			}
		}
	}
	/**
	 * nickname 搜索用户
	 * 传入:用户名从$_GET['nickname']中
	 * @access public
	 * @return void
	 */
	function nickname(){
		$this->autoLayout = false;
		if(isset($_GET['sqlName'])){
			$sql = "SELECT * FROM userinfos as User where nickname like '%{$_GET['sqlName']}%'";
			$result = $this->User->query($sql);
			if(empty($result)){
				echo 0;
				$this->autoRender = false;
				return;
			}
			$this->handle_tag($result);
			$this->set("users",$result);
		}
	}
	/**
	 * content 通过文章内容搜索文章
	 * 传入:内容从$_GET['content']中传入
	 * 返回:
	 *     成功:返回一个包含博客json数组
	 *     失败:返回0
	 * @access public
	 * @return void
	 */
	function content(){
		$this->autoLayout = false;
		$this->autoRender = false;
		if(isset($_GET['sqlName'])){
			$sql = "SELECT * FROM blogs as Blog where content like'%{$_GET['sqlName']}%' or title like'%{$_GET['sqlName']}%'";
			$result = $this->Blog->query($sql);
			 if(empty($result)){
				 echo '0';
			}else{
				$this->handle_nickname($result);
				echo json_encode($result);
			}
		}
		
	}
}
?>
